//
//  MyHomeController.swift
//  DaRings
//
//  Created by 易先生 on 2022/10/27.
//

import UIKit
import MYModule
import RxViewController
import YWFeedbackFMWK


let KFeedbackAppKey = "24659239"
let KFeedbackAppSecret = "eb0c782f77862a8ac4583d68fae90151"

class MyHomeController: ViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigation.bar.backgroundColor = UIColor.background
    }
    
    override func makeUI() {
        super.makeUI()
        
        view.backgroundColor = UIColor.background
        self.navigation.item.leftBarButtonItem = nil

        view.addSubview(headerView)
        view.addSubview(tableView)
        
        headerView.snp.makeConstraints { make in
            make.top.equalTo(topLayoutGuide.snp.bottom)
            make.leading.trailing.equalToSuperview()
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom)
            make.leading.trailing.bottom.equalToSuperview()
        }
    }
    
    override func bindViewModel() {
        super.bindViewModel()
        
        let input = MyHomeViewModel.Input(viewWillAppear: self.rx.viewWillAppear,
                                              advClick: headerView.unDeviceContainerView.addButton.rx.tap.mapToVoid().asDriverOnErrorJustComplete())

        let output = viewModel.transform(input: input)

        output.hasDevice.drive(headerView.rx.isBinding).disposed(by: rx.disposeBag)
        output.deviceName.drive(headerView.deviceContainerView.deviceName.rx.text).disposed(by: rx.disposeBag)
        output.macAddress.drive(headerView.deviceContainerView.macAddressLabel.rx.text).disposed(by: rx.disposeBag)
        output.deviceState.drive(headerView.deviceContainerView.stateLabel.rx.text).disposed(by: rx.disposeBag)
        output.batteryString.drive(headerView.deviceContainerView.batteryLabel.rx.text).disposed(by: rx.disposeBag)
        output.batteryImgHidden.drive(headerView.deviceContainerView.batteryImg.rx.isHidden).disposed(by: rx.disposeBag)
        output.batteryChargImgHidden.drive(headerView.deviceContainerView.batteryChargImg.rx.isHidden).disposed(by: rx.disposeBag)
        
        output.devicePreviewImage.drive(onNext: {[weak self] in
            
            self?.headerView.deviceContainerView.devicePreviewImageView.sd_setImage(with: $0.url, placeholderImage: $0.placeholdImage)
            
        }).disposed(by: rx.disposeBag)
        
        output.batteryPercent.drive(onNext: {[weak self] batteryPercent in
            
            guard let self = self else { return }
            
            self.headerView.deviceContainerView.layoutIfNeeded()
            
            let headerViewWidth = self.headerView.deviceContainerView.batteryContainer.width
            let width = (headerViewWidth - 1.5 - 2.5) * batteryPercent
            
            self.headerView.deviceContainerView.batteryImg.snp.remakeConstraints { make in
                make.bottom.equalToSuperview().offset(-1.5)
                make.top.left.equalToSuperview().offset(1.5)
                make.right.lessThanOrEqualToSuperview().offset(-2.5)
                make.width.equalTo(width).priority(999)
            }
            
            
        }).disposed(by: rx.disposeBag)
        
        
        headerView.unDeviceContainerView.addButton.rx.tap.subscribe { [weak self] _ in
            guard let `self` = self else {return}
            let vc = BindingController()
            self.navigationController?.pushViewController(vc, animated: true)
        }.disposed(by: rx.disposeBag)
        
        headerView.deviceContainerView.removeButton.rx.tap.subscribe(onNext: { [weak self] in
            guard let `self` = self else { return }
            
            self.showRemoveAlert()
            
        }).disposed(by: rx.disposeBag)
        
        
        output.items.bind(to: tableView.rx.items(cellIdentifier: MyHomeTableCell.reuseIdentifier, cellType: MyHomeTableCell.self)) {row, item, cell in
            
            cell.bind(to: item)
            
        
        }.disposed(by: rx.disposeBag)
        
        
        tableView.rx.itemSelected.subscribe(onNext: { [weak self] IndexPath in
            guard let self = self else { return }
            let item = self.viewModel.showItems[IndexPath.row]
            self.gotoViewController(with: item)
        }).disposed(by: rx.disposeBag)
        
        
    }
    
    private func gotoViewController(with item: MyHomeItem) {
        switch item.type {
        case .goal:
            let vc = GoalSetupController()
            self.navigationController?.pushViewController(vc, animated: true)
        case .profile:
            let vc = ProfileController()
            self.navigationController?.pushViewController(vc, animated: true)
        case .others:
            let vc = OtherController()
            self.navigationController?.pushViewController(vc, animated: true)
        case .firmware:
            let vc = FirmwareController()
            vc.brage = item.brage
            self.navigationController?.pushViewController(vc, animated: true)
//        case .wechatSport:
//            let vc = WechatSportController()
//            self.navigationController?.pushViewController(vc, animated: true)
        case .appleHealth:
            let vc = AppleHealthController()
            self.navigationController?.pushViewController(vc, animated: true)
//        case .feedback:
//            let feedbackKit = BCFeedbackKit.init(appKey: KFeedbackAppKey, appSecret: KFeedbackAppSecret)
//            feedbackKit?.makeFeedbackViewController { (viewController, error) in
//                if viewController != nil {
//                    let nav = UINavigationController.init(rootViewController: viewController!)
//                    nav.modalPresentationStyle = .fullScreen
//                    nav.view.backgroundColor = Colors.title_back
//                    if  #available(iOS 13.0, *) {
//                        let barApp = UINavigationBarAppearance()
//                        barApp.configureWithOpaqueBackground()
//                        barApp.backgroundColor = Colors.title_back
//                        barApp.shadowColor = .clear
//                        self.navigationController?.navigationBar.scrollEdgeAppearance = barApp
//                        self.navigationController?.navigationBar.standardAppearance = barApp
//                    }else{
//                        nav.navigationBar.tintColor = Colors.title_back
//                        self.navigationController?.navigationBar.shadowImage = UIImage()
//                    }
//                    nav.navigationBar.isTranslucent = false
//                    viewController?.closeBlock = { aParentController in
//                        aParentController?.dismiss(animated: true)
//                    }
//                    self.present(nav, animated: false)
//                }
//            }
        case .about:
            let vc = AboutusController()
            self.navigationController?.pushViewController(vc, animated: true)
        }
                                                          
    }
    
    private func showRemoveAlert() {
        let alert = UIAlertController(title: "device_bound_remove_watch_hint".language,
            message: "",
            preferredStyle: UIAlertController.Style.alert)

        let okaction = UIAlertAction(title: "dialog_confirm".language, style: UIAlertAction.Style.default) { _ in
            
            let deviceInfo = DeviceInfo.current()
                deviceInfo.unbind()
                BluetoothManager.shared.remove {[weak self] state in
                guard let `self` = self else {return }
                /// 解除绑定
                    self.headerView.isBinding = deviceInfo.isBind
                    self.viewWillAppear(false)
            }
        }

        let cancel = UIAlertAction(title: "page_cancel".language, style: UIAlertAction.Style.cancel, handler: nil)
        alert.addAction(okaction)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
    
    
    private lazy var viewModel: MyHomeViewModel = {
        let ViewModel = MyHomeViewModel()
        return ViewModel
    }()
    
    private lazy var headerView: MyHomeDeviceHeaderView = {
        let headerView = MyHomeDeviceHeaderView()
        return headerView
    }()
    

    private lazy var tableView: TableView = {
        let view = TableView.init(frame: .zero, style: .plain)
        view.register(MyHomeTableCell.self, forCellReuseIdentifier: MyHomeTableCell.reuseIdentifier)
        view.rowHeight = UITableView.automaticDimension
        view.separatorColor = UIColor.assist_D0D0D0
        view.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        view.showsVerticalScrollIndicator = false
        view.backgroundColor = .clear
        return view
    }()

}
